<?php

namespace Home\Controller;

use Think\Controller;

class PublicController extends Controller {

    public function pay() {
        if (IS_POST) {
            $symbol = I('post.symbol') == 1 ? 1 : 0;
            $unit_name = "积分";
            if ($symbol == 1) {
                $unit_name = "火币";
            }
            //页面上通过表单选择在线支付类型，支付宝为alipay 财付通为tenpay
            $paytype = I('post.paytype');

            $pay = new \Think\Pay($paytype, C('payment.' . $paytype));
            $points_item = I("post.points_item");
            $order_money = I('post.money', 200, 'int'); //支付金额
            if ($order_money < 5) {
                $order_money = 5;
            }
            if ($points_item == 'custom') {
                if ($symbol == 1) {
                    $points = getMoneyHuobi($order_money);
                } else {
                    $points = getMoneyPoints($order_money);
                }
            } else {
                $pay_points = M("pay_points")->where("id = " . $points_item . "")->find();
                $order_money = $pay_points['money'];
                $points = $pay_points['points'];
            }



            $title = "充值" . $points . $unit_name;
            $order_no = $pay->createOrderNo();
            $url_return = C("SITE_URL") . "Member/order";
            $url_notify = C("SITE_URL") . "Public/notify";
            M("Pay")->add(array(
                'out_trade_no' => $order_no,
                'symbol' => $symbol,
                'money' => $order_money,
                'status' => 0,
                'uid' => getUserid(),
                'points' => $points,
                'addtime' => time(),
                'update_time' => time()
            ));
            $vo = new \Think\Pay\PayVo();
            $vo->setBody("充值" . $unit_name)->setFee($order_money)->setOrderNo($order_no)->setTitle($title)->setUrl($url_return)->setCallback($url_notify);
            echo $pay->buildRequestForm($vo);
        }
    }

    public function pay_month() {

        if (IS_POST) {
            $paytype = I('post.paytype');
            $pay = new \Think\Pay($paytype, C('payment.' . $paytype));
            $order_no = $pay->createOrderNo();

            $id = I("post.month");
            $pay_month = M("pay_month")->where("id = " . $id . "")->find();
            $order_money = $pay_month['money'];
            $month = $pay_month['month'];
            $name = $pay_month['name'];
            M("Order_month")->add(array(
                'order_num' => $order_no,
                'month' => $month,
                'money' => $order_money,
                'status' => 0,
                'uid' => getUserid(),
                'addtime' => time(),
                'update_time' => 0
            ));
            $title = "充值" . $name . "会员";
            $body = $id;
            $url_return = C("SITE_URL") . "Member/pay";
            $url_notify = C("SITE_URL") . "Public/notify_month";
            $vo = new \Think\Pay\PayVo();
//            $vo->setFee($money)
//                    ->setOrderNo($order_no)
//                    ->setTitle($title)->setBody($month);
            $vo->setBody($body)->setFee($order_money)->setOrderNo($order_no)->setTitle($title)->setUrl($url_return)->setCallback($url_notify);
            echo $pay->buildRequestForm($vo);
        }
    }

    public function wxpay() {


        include_once "Public/weixinpay/lib/WxPay.Api.php";
        include_once "Public/weixinpay/pay/WxPay.NativePay.php";

        $id = I("post.month");

        $pay_month = M("pay_month")->where("id = " . $id . "")->find();
        $order_money = $pay_month['money'];

        $name = $pay_month['name'];
        $NativePay = new \NativePay();
        $order_num = date("YmdHis") . rand(10000, 99999);

        $title = "充值" . $name . "会员";
        M("order_month")->add(array(
            'order_num' => $order_num,
            'month' => $pay_month['month'],
            'money' => $order_money,
            'status' => 0,
            'uid' => getUserid(),
            'addtime' => time(),
            'update_time' => 0
        ));
        $url_notify = "http://www.sucaihuo.com/Public/notify_wx_month";
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($title);   //商品描述
        $input->SetAttach(""); //附加数据
        $input->SetOut_trade_no($order_num);
        $input->SetTotal_fee($order_money * 100); // 总金额
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag(""); //商品标记，代金券或立减优惠功能的参数，说明详见
        $input->SetNotify_url($url_notify);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($order_num); //商品ID 或订单编号
        $result = $NativePay->GetPayUrl($input);

        $code_url = $result["code_url"];
        $this->assign("code_url", urlencode($code_url));
        $this->assign("order_num", $order_num);
        $this->display();
    }

    private function gift_points($order_month) {
        if ($order_month['month'] == 10000) {
            $lastid_gift = M("Pay")->add(array(
                'out_trade_no' => 'gift_' . date("YmdHis") . rand(10000, 99999),
                'symbol' => 0,
                'money' => 0.1,
                'status' => 1,
                'uid' => $order_month['uid'],
                'points' => 700,
                'addtime' => time(),
                'update_time' => time()
            ));
            if ($lastid_gift > 0) {
                M("user")->where("id = " . $order_month['uid'] . "")->setInc("money", 700);
            }
        }
    }

    public function check_month() {
        $order_num = I("post.order_num");
        $order_month = M("order_month")->field("id")->where("order_num = '" . $order_num . "' AND status = 1")->find();
        echo $order_month['id'];
    }

    public function check_points() {
        $order_num = I("post.order_num");
        $order_info = M("pay")->where("out_trade_no = '" . $order_num . "' AND status = 1")->find();
        echo $order_info ? 1 : 0;
    }

    public function pay_huobi() {
        if (IS_POST) {

            //页面上通过表单选择在线支付类型，支付宝为alipay 财付通为tenpay
            $paytype = I('post.paytype');

            $pay = new \Think\Pay($paytype, C('payment.' . $paytype));
            $huobi_id = I("post.huobi_id");

            if ($huobi_id > 0) {
                $pay_huobi = M("pay_huobi")->where("id = " . $huobi_id . "")->find();
                $order_money = $pay_huobi['money'];
                $points = $pay_huobi['points'];
            } else {
                $order_money = I("post.money2", 10, 'int') > 5 ? I("post.money2", 10, 'int') : 5;
                $points = $order_money;
            }

            $title = "充值" . $points . "火币";
            $order_no = $pay->createOrderNo();
            $url_return = C("SITE_URL") . "Member/order";
            $url_notify = C("SITE_URL") . "Public/notify";
            M("pay")->add(array(
                'out_trade_no' => $order_no,
                "symbol" => 1,
                'money' => $order_money,
                'status' => 0,
                'uid' => getUserid(),
                'points' => 0,
                'huobi' => $points,
                'addtime' => time(),
                'update_time' => 0
            ));
            $vo = new \Think\Pay\PayVo();
            $vo->setBody("充值火币")->setFee($order_money)->setOrderNo($order_no)->setTitle($title)->setUrl($url_return)->setCallback($url_notify);
            echo $pay->buildRequestForm($vo);
        }
    }

    public function wxpay_huobi() {


        include_once "Public/weixinpay/lib/WxPay.Api.php";
        include_once "Public/weixinpay/pay/WxPay.NativePay.php";

        $unit_name = "火币";
        $huobi_id = I("post.huobi_id");

        if ($huobi_id > 0) {
            $pay_huobi = M("pay_huobi")->where("id = " . $huobi_id . "")->find();
            $order_money = $pay_huobi['money'];
            $points = $pay_huobi['points'];
        } else {
            $order_money = I("post.money2", 10, 'int') > 5 ? I("post.money2", 10, 'int') : 5;
            $points = $order_money;
        }


        $NativePay = new \NativePay();
        $order_no = date("YmdHis") . rand(10000, 99999);

        $title = "充值" . $points . $unit_name;
        $pay_data = array(
            'out_trade_no' => $order_no,
            "symbol" => 1,
            'money' => $order_money,
            'status' => 0,
            'uid' => getUserid(),
            'huobi' => $points,
            'addtime' => time(),
            'update_time' => 0,
            'points' => 0
        );

        M("pay")->add($pay_data);
//       echo M("pay")->getlastsql();
        $url_notify = "http://www.sucaihuo.com/Public/wxpay_huobi_notify";
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($title);   //商品描述
        $input->SetAttach(""); //附加数据
        $input->SetOut_trade_no($order_no);
        $input->SetTotal_fee($order_money * 100); // 总金额
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag(""); //商品标记，代金券或立减优惠功能的参数，说明详见
        $input->SetNotify_url($url_notify);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($order_no); //商品ID 或订单编号
        $result = $NativePay->GetPayUrl($input);
//        print_r($result);exit;
        $code_url = $result["code_url"];
        $this->assign("code_url", urlencode($code_url));
        $this->assign("order_num", $order_no);
        $this->display();
    }

    private function gift_month($userid, $money) {
        $pay_points = M("pay_points")->field("vip_month")->where("money = " . $money . "")->find();
        if ($pay_points['vip_month'] > 0) {
            $userinfo = M("user")->field("vip_time")->where("id = " . $userid . "")->find();
            $vip_time = $userinfo['vip_time'];
            if ($vip_time < time()) {
                $vip_time = time();
            }
            $vip_time_last = $vip_time + $pay_points['vip_month'] * 3600 * 24 * 30;
            M("user")->where("id = " . $userid . "")->save(array("vip_time" => $vip_time_last));
        }
    }

    //回调


    public function notify_wx_month() {
        $simple = json_decode(json_encode(simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA)), true);


        $out_trade_no = $simple['out_trade_no'];
        $trade_num = $simple['out_trade_no'];
        if ($out_trade_no && $trade_num) {
            $order_month = M("order_month")->field("id,uid,money,month,order_num")->where("order_num = '" . $out_trade_no . "' AND status = 0")->find();
            if ($order_month) {
                M("order_month")->where(array('order_num' => $out_trade_no))->save(array("status" => 1, "update_time" => time(), "trade_num" => $trade_num));
                $userinfo = M("user")->field("vip_time")->where("id = " . $order_month['uid'] . "")->find();
                $vip_time = $userinfo['vip_time'];
                if ($vip_time < time()) {
                    $vip_time = time();
                }
                $vip_time_last = $vip_time + $order_month['month'] * 3600 * 24 * 30;
                M("user")->where("id = " . $order_month['uid'] . "")->save(array("vip_time" => $vip_time_last));
                $this->gift_points($order_month);
            }
            exit;
        }
    }

    public function wxpay_huobi_notify() {
        $simple = json_decode(json_encode(simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        $out_trade_no = $simple['out_trade_no'];

        $info = M("pay")->field("uid,huobi,money")->where("out_trade_no = '" . $out_trade_no . "' AND status = 0")->find();
        if ($info) {
            $data['status'] = 1;
            $data['update_time'] = time();

            M("pay")->where(array('out_trade_no' => $out_trade_no))->save($data);
            $huobi = $info['huobi'];

            addPoints("pay", $huobi, $info['uid'], 5, 1, 0, 0, 0, 1);
        }
        $this->redirect("Member/order");
        exit;
    }

    public function wxpay_points_notify() {
        $simple = json_decode(json_encode(simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA)), true);


        $out_trade_no = $simple['out_trade_no'];
        $data['status'] = 1;
        $data['update_time'] = time();
        $info = M("pay")->field("uid,points,money")->where("out_trade_no = '" . $out_trade_no . "' AND status = 0")->find();
        if ($info['uid'] == 1) {
//            file_put_contents("simple2.txt", "json: " . date("Y-m-d H:i:s") . json_encode($simple) . "\r\n", FILE_APPEND);
        }
        if ($info) {
            M("pay")->where(array('out_trade_no' => $out_trade_no))->save($data);
            $points = $info['points'];

            addPoints("pay", $points, $info['uid'], 5, 1);
            $userid = $info['uid'];
            $money = $info['money'];
            $this->gift_month($userid, $money);
        }
        $this->redirect("Member/order");
        exit;
    }

    /**
     * 支付结果返回
     */
    public function notify() {
        if ($_POST || $_GET) {
            $out_trade_no = I("post.out_trade_no");
            $data['status'] = 1;
            $data['update_time'] = time();
            $info = M("pay")->field("uid,points,money,symbol,huobi")->where("out_trade_no = '" . $out_trade_no . "' AND status = 0")->find();
            if ($info) {
                M("pay")->where(array('out_trade_no' => $out_trade_no))->save($data);
                if ($info['symbol'] == 1) { //充值火币
                    $points = $info['huobi'];
                    addPoints("pay", $points, $info['uid'], 5, 1, 0, 0, 0, 1);
                } else {
                    $points = $info['points'];
                    addPoints("pay", $points, $info['uid'], 5, 1);
                    $userid = $info['uid'];
                    $money = $info['money'];
                    $this->gift_month($userid, $money);
                }
            }
            $this->redirect("Member/order");
            exit;
        }
    }

    public function notify_month() {

        $out_trade_no = I("post.out_trade_no");
        $trade_num = I("post.trade_no");
        if ($out_trade_no && $trade_num) {
            $order_month = M("order_month")->field("id,uid,money,month,order_num")->where("order_num = '" . $out_trade_no . "' AND status = 0")->find();
            if ($order_month) {
                M("order_month")->where(array('order_num' => $out_trade_no))->save(array("status" => 1, "update_time" => time(), "trade_num" => $trade_num));
                $userinfo = M("user")->field("vip_time")->where("id = " . $order_month['uid'] . "")->find();
                $vip_time = $userinfo['vip_time'];
                if ($vip_time < time()) {
                    $vip_time = time();
                }
                $vip_time_last = $vip_time + $order_month['month'] * 3600 * 24 * 30;
                M("user")->where("id = " . $order_month['uid'] . "")->save(array("vip_time" => $vip_time_last));
                $this->gift_points($order_month);
            }
            exit;
        }
    }
public function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return 1;
    } else {
        return 0;
    }
}
    public function wxpay_points() {
      $userid = getUserid();
      if($userid == 1){
          echo 1;exit;
      }
//        $is_weixin = $this->is_weixin();
//          if($is_weixin == 1){
//        $this->jsapi_order('points');
//        exit;
//          }
        include_once "Public/weixinpay/lib/WxPay.Api.php";
        include_once "Public/weixinpay/pay/WxPay.NativePay.php";



        $symbol = I('post.symbol') == 1 ? 1 : 0;
        $unit_name = "积分";
        if ($symbol == 1) {
            $unit_name = "火币";
        }



        $points_item = I("post.points_item");
        $order_money = I('post.money', 200, 'int'); //支付金额
        if ($order_money < 5) {
            $order_money = 5;
        }
        if ($points_item == 'custom') {
            if ($symbol == 1) {
                $points = getMoneyHuobi($order_money);
            } else {
                $points = getMoneyPoints($order_money);
            }
        } else {
            $pay_points = M("pay_points")->where("id = " . $points_item . "")->find();
            $order_money = $pay_points['money'];
            $points = $pay_points['points'];
        }


        $NativePay = new \NativePay();
        $order_no = date("YmdHis") . rand(10000, 99999);

        $title = "充值" . $points . $unit_name;
        M("Pay")->add(array(
            'out_trade_no' => $order_no,
            'symbol' => $symbol,
            'money' => $order_money,
            'status' => 0,
            'uid' => getUserid(),
            'points' => $points,
            'addtime' => time(),
            'update_time' => time()
        ));
        $url_notify = "http://www.sucaihuo.com/Public/wxpay_points_notify";
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($title);   //商品描述
        $input->SetAttach(""); //附加数据
        $input->SetOut_trade_no($order_no);
        $input->SetTotal_fee($order_money * 100); // 总金额
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag(""); //商品标记，代金券或立减优惠功能的参数，说明详见
        $input->SetNotify_url($url_notify);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($order_no); //商品ID 或订单编号
        $result = $NativePay->GetPayUrl($input);
        $code_url = $result["code_url"];
        $this->assign("code_url", urlencode($code_url));
        $this->assign("order_num", $order_no);
        $this->display();
    }

    public function jsapi_order($mtype) {
      echo 111;exit;
        $order_money = 0.1; //订单金额 元
        $order_no = time() . rand(1, 1000);
 


        $url_notify = C("ROOT_URL") . "Notify/pay_weixin"; //微信支付回调地址

        include_once "Public/weixinpay/lib/WxPay.Api.php";
        include_once "Public/weixinpay/WxPay.JsApiPay.php";
        //①、获取用户openid
        echo 111;exit;
        $tools = new \JsApiPay();
        echo $tools->GetOpenid();exit;
        $openId = session("open_id") ? session("open_id") : $tools->GetOpenid();
  
        //$openId = $tools->GetOpenid();
//②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("暂无");
        $input->SetOut_trade_no($order_no);
        $input->SetTotal_fee($order_money * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($url_notify);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);

        $jsApiParameters = $tools->GetJsApiParameters($order);



        $this->assign("jsApiParameters", $jsApiParameters);

        $this->assign("order_no", $order_no);
        $this->display("Public:jsapi_order");
    }

}
